package com.jeanbart.factory.api.apiImpl;


import com.jeanbart.bean.Player;
import com.jeanbart.factory.api.wowsAPI;
import lombok.SneakyThrows;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

public class api360 implements wowsAPI, Callable {

    private Player player;
    public api360(){}
    public api360(Player player){
        this.player = player;
    }

    @Override
    public Object call() throws Exception {
        switch(player.getStep()){
            case 1: getUid(player);//这一步不break
            case 2: PlayerInfo(player);break;
            case 3: getShipRate(player);
        }
        return player;
    }


    @SneakyThrows
    @Override
    public void getUid(Player player){
        String Uid ="";
        String name = player.getAccountName();
        String searchUrl = "https://wowsgame.cn/zh-cn/community/accounts/search?search="+ URLEncoder.encode(name,"UTF-8");
        URL url= null;
        try {
            url = new URL(searchUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.addRequestProperty("X-Requested-With","XMLHttpRequest");
        connection.setInstanceFollowRedirects(true);
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里返回的是重定向script脚本重定向到战绩页面
        String ret = new BufferedReader(new InputStreamReader(in)).lines()
                .parallel().collect(Collectors.joining(System.lineSeparator()));
        if(ret.indexOf("<script>")==-1){
            player.setUid("未找到");
        }
        else{
            Uid = ret.substring(ret.indexOf("accounts/")+9).substring(0,10);
            player.setUid(Uid);
        }
    }

    @Override
    public void PlayerInfo(Player player){
        String Uid = player.getUid();
        //隐藏战绩的
        if(Uid.equals("未找到")){
            player.setCount("-1");
            player.setWinCount("-1");
            player.setRate(-1);//去掉自带的百分号
            return;
        }
        String playerURL = "https://wowsgame.cn/zh-cn/community/accounts/tab/pvp/overview/"+Uid;
        URL url= null;
        try {
            url = new URL(playerURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.addRequestProperty("X-Requested-With","XMLHttpRequest");
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String html = new BufferedReader(new InputStreamReader(in)).lines()
                .parallel().collect(Collectors.joining(System.lineSeparator()));
        Document doc= Jsoup.parse(html);
        Elements e=doc.select("._values");
        Elements div = e.get(0).select("div>div");
        player.setCount(div.get(0).text());
        String rate=div.get(1).text();
        player.setRate((Double.parseDouble(rate.substring(0,rate.length()-1)))/100);//去掉自带的百分号
    }

    @Override
    public void getUids(List<Player> list) {
    }

    @Override
    public void PlayerInfos(List<Player> list) {
    }

    @Override
    public void getShipRate(Player player) {
        String Uid = player.getUid();
        String shipId = player.getShipId();
        //隐藏战绩的
        if(Uid.equals("未找到")){
            player.setShipCount("-1");
            player.setShipWinCount("-1");
            player.setShipRate(-1);//去掉自带的百分号
            return;
        }
        String playerURL = "https://wowsgame.cn/zh-cn/community/accounts/tab/pvp/ships/"+Uid;
        URL url= null;
        try {
            url = new URL(playerURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.addRequestProperty("X-Requested-With","XMLHttpRequest");
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long startTime = System.currentTimeMillis();
        String html = new BufferedReader(new InputStreamReader(in)).lines()
                .parallel().collect(Collectors.joining(System.lineSeparator()));
        long endTime = System.currentTimeMillis();
        //System.out.println("下载时间="+(endTime-startTime)+"ms");
        Document doc= Jsoup.parse(html);
        Elements e=doc.select("tr[ref^=\""+shipId+"\"]");
        player.setShipCount(e.select("tbody > tr:nth-child(1) ._value>span").first().text());
        player.setShipWinCount(e.select("tbody > tr:nth-child(2) ._value>span").first().text());
        if(!Double.valueOf(player.getShipCount()).equals(0)) {
            Double rate = Double.valueOf(player.getShipWinCount()) / Double.valueOf(player.getShipCount());
            player.setShipRate(rate);
        }else{
            player.setShipRate(0);
        }
    }
}
